/**
 * 抽样样本列表
 */

import { Button, ScrollView } from "devextreme-react";
import { forwardRef, useContext, useEffect, useMemo, useRef, useState } from "react";
import { ManualSampleParams, OverallMode, SampledResult, SampleParameterValues, ProjectOverallProps, SampleStepInfo, SampleTable, SamplingSampleListProps, RetDataInfo } from "../typing";
import { SampleStepInfoContext } from "./samplingRecordPopup";
import { getSampledResultTable1, getSampledResultTable2, getTextFieldsValues, getWhereSqlBySampleListOfTable, leftVerticalDivStyle } from "./SampleParameter/NonStatSampleService";
import SamplingProjectOverall from "./samplingProjectOverall";
import { HocAntTabsFillStyleTab } from "~/public/cpas-ui/components-ui/ant-components/AntTab";
import AntTabsPanel from "~/public/cpas-ui/components-ui/ant-components/AntTab/AntTabsPanel";
import { getAllSampledWhereSql, getTypedSampleList, updateAllSampleType, updateManualAddParams } from "./samplingSampleListService";
import { msgError, msgInfo } from "@/utils/msg";
import { consts } from "../consts";
import { DevGrid } from "~/public/cpas-ui";
import { IColumnProps } from "devextreme-react/data-grid";
import { getSampleSourceColumsOfExists } from "./samplingSourceService";
import { useModel } from "umi";

import './../index.less'
import { getDeleteGridSelectRows } from "./service";
import { getSampleOverallWhereSQL, iniFormQueryAndAdvParams } from "./samplingProjectOverallService";


export const SamplingSampleList = forwardRef((props: SamplingSampleListProps, ref: any) => {

    //上级传入的抽样参数(注:此组件中sampleStepInfo.sampleParameterValues值可用)
    const sampleStepInfo: SampleStepInfo = useContext(SampleStepInfoContext);
    const sampleParameterValues: SampleParameterValues = sampleStepInfo.sampleParameterValues as any;//确定有值了

    //值或步骤号不对

    if (!sampleParameterValues || sampleStepInfo.stepCurrent != 2) {
        return;
    }

    const { initialState } = useModel('@@initialState');
    const { dbname, sjnd } = initialState?.curPart as any;
    //各个tab标题表格加载
    const tabsTitle = { sampled: '需测试的全部项目', notSample: '未抽取的项目', };
    const [tabActiveKey, setTabActiveKey] = useState<string>('sampled');

    const [focusedRowIndex, setFocusedRowIndex] = useState<number>(0)
    const [confirmDelete, setConfirmDelete] = useState<boolean>(true)
    //已抽取的全部样本:抽样方法抽取的、重大项目、特殊项目、手工增加的
    const [sampledAllSampleSize, setSampledAllSampleSize] = useState<number>(0)
    const manualSampleParamsGridRef = useRef<any>();
    const sampledProjectOverallRef = useRef<any>(null);
    const notSampleProjectOverallRef = useRef<any>(null);
    const [manualSampleDataSource, setManualSampleDataSource] = useState<any[]>(sampleParameterValues.manualSampleParams?.sampledList || [])

    const [params, setParams] = useState<{
        sampledProjectOverallProps: ProjectOverallProps,
        notSampleProjectOverallProps: ProjectOverallProps
        manualSampleParamsColumns: any[],
        manualAddParams: ManualSampleParams,
        textFieldsArray: string[]
        numFieldsArray: string[]
    }>()
    useEffect(() => {
        //获取所有已抽的条件,抽样+金额重大+特殊项目
        let sampledResult: SampledResult = sampleParameterValues.sampledResult as any;

        getWhereSqlBySampleListOfTable(sampleStepInfo, sampledResult.sampledList, dbname).then(
            async (retSqlInfo: { sampledWhereSql: string, notSampledWhereSql: string }) => {

                const typedSampleInfo = await getTypedSampleList(sampleStepInfo, sampleParameterValues, false);
                const allSampledWhereSql = getAllSampledWhereSql(sampleParameterValues, retSqlInfo.sampledWhereSql)
                //已抽样的属性
                let sampledProjectOverallProps: ProjectOverallProps = sampleStepInfo.projectOverallProps as any;//确定有值了
                let overallWhereSQL = getSampleOverallWhereSQL(sampledProjectOverallProps.curWhereSqlParams || {});//获取sql
                sampledProjectOverallProps = JSON.parse(JSON.stringify(sampledProjectOverallProps));//生成一个新的
                sampledProjectOverallProps.overallMode = OverallMode.sampledList;

                sampledProjectOverallProps.fixedWhereSql = overallWhereSQL + allSampledWhereSql;

                iniFormQueryAndAdvParams(sampledProjectOverallProps);

                // console.log('sampleParameterValues.manualSampleParams', sampleParameterValues.manualSampleParams)

                const textFieldsArray: string[] = sampledProjectOverallProps.curSampleTable?.sampleTextFieldsArray || [];
                const numFieldsArray: string[] = sampledProjectOverallProps.curSampleTable?.sampleNumFieldsArray || [];


                //未抽样的要排除 金额重大项目+特殊项目

                //金额重大项目
                let allNotSampledWhereSql = retSqlInfo.notSampledWhereSql;
                if (sampleParameterValues.amountMajorWhereSql) {
                    allNotSampledWhereSql += ` and not   (1=1  ${sampleParameterValues.amountMajorWhereSql}) `;
                }
                //特殊项目
                if (sampleParameterValues.specialWhereSql) {
                    allNotSampledWhereSql += ` and not (1=1  ${sampleParameterValues.specialWhereSql})`
                }


                let notSampleProjectOverallProps: ProjectOverallProps = sampleStepInfo.projectOverallProps as any;//确定有值了
                notSampleProjectOverallProps = JSON.parse(JSON.stringify(notSampleProjectOverallProps));//生成一个新的
                notSampleProjectOverallProps.overallMode = OverallMode.sampleListManualAdd;//手工添加
                notSampleProjectOverallProps.fixedWhereSql = overallWhereSQL + allNotSampledWhereSql;
                iniFormQueryAndAdvParams(notSampleProjectOverallProps);
                let manualAddParams: ManualSampleParams = sampleParameterValues.manualAddParams as any;

                setManualSampleDataSource([...manualAddParams.sampledList])

                //手工已选样本的属性
                const sampleTable: SampleTable = notSampleProjectOverallProps.curSampleTable as any;
                const sampleSourceFields = sampleTable.sampleAllFieldsArray;// await getSampleSourceFields(dbname, sampleTable.tableName);
                const manualSampleParamsColumns: IColumnProps[] = getSampleSourceColumsOfExists(sampleTable, sampleSourceFields, true);
                manualSampleParamsColumns.push({ caption: '操作', type: 'buttons', fixed: true, fixedPosition: 'left' })

                //执行手工增加
                async function doManualAddSample(rowData: any) {
                    const values1 = getTextFieldsValues(rowData, textFieldsArray);
                    const manualAddParamsSampledList: any[] = manualSampleParamsGridRef.current.instance.getDataSource()._items;

                    const findIndex = manualAddParamsSampledList.findIndex(item2 => {
                        let values2 = getTextFieldsValues(item2, textFieldsArray);
                        return values1 == values2
                    })
                    if (findIndex == -1) {
                        manualAddParamsSampledList.push({ ...rowData });
                        manualAddParams.sampledList = manualAddParamsSampledList;
                        //新加或删除后,更新手工增加样本的参数
                        await updateManualAddParams(props, manualAddParams, sampleStepInfo, sampleParameterValues, textFieldsArray, numFieldsArray);

                        sampleParameterValues.sampledAllSampleSize = (sampleParameterValues.sampledAllSampleSize || 0) + 1 //用于保存
                        setManualSampleDataSource([...manualAddParamsSampledList])
                        msgInfo('添加成功!')

                    } else {
                        setFocusedRowIndex(findIndex)
                        msgError(`此行数据已经存在!`)
                    }

                }
                //手工添加样本的事件
                notSampleProjectOverallProps.events = {
                    onRowDblClick: async (e: any) => {
                        doManualAddSample(e.data);
                    },
                    onManualAddSample: async (e: any) => {
                        doManualAddSample(e.row.data);
                    }
                }
                sampledProjectOverallProps.exportFileNameOnly = tabsTitle.sampled;
                let isNeedExecOnLoadData = true;
                //已抽样本事件
                sampledProjectOverallProps.events = {
                    onLoadData: (retDataInfo: RetDataInfo) => {

                        //更新样本全部类型:金额重大/特殊样本/手工增加/正常样本
                        updateAllSampleType(typedSampleInfo, retDataInfo.rowsData, textFieldsArray, [])
                        if (isNeedExecOnLoadData || sampleParameterValues.sampledAllSampleSize == 0) {
                            //已抽取的全部样本:抽样方法抽取的、重大项目、特殊项目、手工增加的
                            setSampledAllSampleSize(retDataInfo.totalCount)//用于显示
                            sampleParameterValues.sampledAllSampleSize = retDataInfo.totalCount;//用于保存
                            isNeedExecOnLoadData = false;
                        }

                    },
                    onBeforeExportData: (retDataInfo: RetDataInfo) => {
                        updateAllSampleType(typedSampleInfo, retDataInfo.rowsData, textFieldsArray, [])
                    }
                }

                setParams({
                    sampledProjectOverallProps,
                    notSampleProjectOverallProps,
                    manualSampleParamsColumns,
                    manualAddParams,
                    textFieldsArray,
                    numFieldsArray,
                });


            })
    }, [sampleParameterValues.manualAddParams])


    return <div className="SamplingSampleList" style={{ height: '85vh' }}>
        <HocAntTabsFillStyleTab key="sampled"
            defaultActiveKey="sampled"
            onChange={(newTabActiveKey: string) => {
                setTabActiveKey(newTabActiveKey)
            }}

        >
            {/* 已抽样本 */}
            <AntTabsPanel key='sampled' tab={`${tabsTitle.sampled}(${sampledAllSampleSize})`}>
                {tabActiveKey == 'sampled' && params &&
                    <ScrollView id="sampledScrollview" height='100%'  >
                        <div style={{ marginRight: 10 }}  >
                            <SamplingProjectOverall
                                ref={sampledProjectOverallRef}
                                propsOfParams={params.sampledProjectOverallProps}
                            // {...params.sampledProjectOverallProps}
                            />
                            <div style={{ marginTop: 25, paddingLeft: 10, paddingRight: 50, borderRadius: 5, border: '1px solid #ccc' }}>
                                {getSampledResultTable1(sampleStepInfo, sampleParameterValues, true)}
                                {getSampledResultTable2(sampleStepInfo, sampleParameterValues)}
                                <div style={{ fontWeight: 'bold' }}>注: 需要测试的全部项目 = 已抽笔数 + 已抽金额重大 + 已抽性质特殊 +  手工添加样本</div>
                            </div>
                        </div>
                    </ScrollView>
                }
                {/*    } */}
            </AntTabsPanel>
            {/* 未抽样本 */}
            <AntTabsPanel key='notSample' tab={tabsTitle.notSample}>

                <ScrollView id="notSampleScrollview" height='100%'   >
                    <div style={{ marginRight: 10 }} >
                        {useMemo(() => {
                            //这个就再重复渲染了
                            return params ?
                                <SamplingProjectOverall
                                    ref={notSampleProjectOverallRef}
                                    propsOfParams={params.notSampleProjectOverallProps}
                                />
                                : null
                        }, [params?.notSampleProjectOverallProps?.fixedWhereSql])}

                        {tabActiveKey == 'notSample' && params &&
                            <div id='notSampleScrollviewDiv' className="itemBoxDispalyLeft"
                                style={{ marginLeft: 0, marginTop: 0, height: '85%', border: '1px solid #e5e5e5', borderRadius: 5, width: '100%' }}  >
                                <div style={{ ...leftVerticalDivStyle, paddingTop: 0 }} >
                                    <div>手</div>
                                    <div>工</div>
                                    <div>样</div>
                                    <div>本</div>
                                    <div style={{ marginLeft: -3 }}>({(manualSampleDataSource || []).length})</div>
                                    <div className="AuditSelectSampleDel"
                                        style={{
                                            marginLeft: -5,
                                            marginTop: 5,
                                            marginBottom: 5
                                        }}>
                                        <Button icon='iconfont icon-del'
                                            width={60}
                                            height={32}
                                            hint='删除选中项'
                                            onClick={e => {
                                                getDeleteGridSelectRows(manualSampleParamsGridRef, setConfirmDelete, async (deleteRowKeys: any[]) => {

                                                    const newSampledList = params.manualAddParams.sampledList.filter(item => !deleteRowKeys.includes(item.rn));
                                                    params.manualAddParams.sampledList = newSampledList;
                                                    await updateManualAddParams(props, params.manualAddParams,
                                                        sampleStepInfo, sampleParameterValues, params.textFieldsArray, params.numFieldsArray);

                                                    sampleParameterValues.sampledAllSampleSize = (sampleParameterValues.sampledAllSampleSize || 0) - deleteRowKeys.length //用于保存
                                                    if (sampleParameterValues.manualAddParams) {
                                                        debugger
                                                        sampleParameterValues.manualAddParams.sampledList = newSampledList
                                                    }
                                                    setManualSampleDataSource([...params.manualAddParams.sampledList])
                                                })
                                            }}
                                        />
                                    </div>
                                </div>
                                <div id='notSampleScrollviewDiv' style={{ marginLeft: 0, marginTop: 0 }}  >
                                    <DevGrid.RangeTap
                                        className={` PaperDevSortableGrid devHeadersCenter `}
                                        height={'150px'}
                                        id="manualSampleDataSource"
                                        width={() => {
                                            let notSampleScrollview = document.getElementById('notSampleScrollviewDiv');
                                            if (notSampleScrollview) {
                                                return notSampleScrollview.offsetWidth - 50
                                            } else {
                                                return 1024
                                            }

                                        }} //缩放比例
                                        // style={{ marginRigth: 10}}
                                        dataSource={manualSampleDataSource}
                                        keyExpr="rn"
                                        ref={manualSampleParamsGridRef}
                                        isRemote={true}
                                        columns={params.manualSampleParamsColumns}//不加这个,setSampleSourceDataColumns会导致这个报错

                                        showBorders={false}
                                        showRowLines={true}
                                        showColumnLines={true}
                                        allowColumnResizing={true}
                                        loadPanel={{ enabled: true }}
                                        columnMinWidth={30}
                                        defaultFocusedRowIndex={0}
                                        searchPanel={{ visible: false, width: 100 }}
                                        headerFilter={{ texts: { ok: '确定' } }}
                                        disableFirstHeaderSearch={true}
                                        paging={{ enabled: false, pageSize: consts.maxSampleCount }}
                                        //focusedRowEnabled={true} 这个属性不能加,会导致数组分页的totalCount不生效
                                        remoteOperations={{ paging: false }} //加这个才能支持远程分页 本地过滤 20230507

                                        renderAsync={true}
                                        selection={{ mode: 'multiple' }}

                                        editing={{ allowDeleting: true, confirmDelete: confirmDelete }}
                                        focusedRowEnabled={true}
                                        focusedRowIndex={focusedRowIndex}

                                        onRowRemoved={async (e: any) => {
                                            if (confirmDelete) {//单行删除
                                                //删除后,要更新后台
                                                const item = e.data;
                                                const values1 = getTextFieldsValues(item, params.textFieldsArray);

                                                const findIndex = params.manualAddParams.sampledList.findIndex(item2 => {
                                                    let values2 = getTextFieldsValues(item2, params.textFieldsArray);
                                                    return values1 == values2
                                                })

                                                if (findIndex > -1) {
                                                    params.manualAddParams.sampledList.splice(findIndex, 1)
                                                    await updateManualAddParams(props, params.manualAddParams,
                                                        sampleStepInfo, sampleParameterValues, params.textFieldsArray, params.numFieldsArray);

                                                    sampleParameterValues.sampledAllSampleSize = (sampleParameterValues.sampledAllSampleSize || 0) - 1 //用于保存

                                                    setManualSampleDataSource([...params.manualAddParams.sampledList])
                                                }
                                            }

                                        }}

                                    />
                                </div>

                            </div>
                        }
                    </div>
                </ScrollView>
            </AntTabsPanel>
        </HocAntTabsFillStyleTab>
    </div>

});
